package com.lab.utils.imageupload.imp;

import android.text.TextUtils;
import android.util.Log;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.lab.logtrack.AppLog;
import com.lab.rtenvironment.AppCoreRuntime;
import com.lab.utils.ThreadUtil;
import com.lab.utils.imageupload.model.OssTokenObject;

import java.io.File;
import java.util.Calendar;
import java.util.HashMap;

/**
 * Created by ak
 * 支持普通上传
 */
public class OssService {

    private OSS oss;
    private OssTokenObject ossTokenObject;
    //根据实际需求改变分片大小
    private final static int partSize = 256 * 1024;


    public OssService() {
    }

    public void initClient(OssTokenObject ossTokenObject) {
        STSGetter credentialProvider = new STSGetter(ossTokenObject);

        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
        OSS oss = new OSSClient(AppCoreRuntime.context, ossTokenObject.getEndpoint(), credentialProvider, conf);
        InitOss(oss);
        this.ossTokenObject = ossTokenObject;
    }


    private void InitOss(OSS _oss) {
        this.oss = _oss;
    }

    public static String getObjectName(String uid, File file) {
        String fileExtName = ".png";
        if (!TextUtils.isEmpty(file.getName()) && file.getName().contains(".")) {
            fileExtName = file.getName().substring(file.getName().lastIndexOf(".") + 1);
        }
        return new StringBuilder(uid).append("-").append(Calendar.getInstance().getTimeInMillis()).append(fileExtName).toString();
    }

    private String getReturnUrl(String objectKey) {
        return String.format("http://%s/%s/%s", ossTokenObject.getEndpoint(), ossTokenObject.getBucket(), objectKey);
    }

    public void asyncPutImage(final String object, String localFile, final UploadCallback uploadCallback) {
        if (object.equals("")) {
            Log.w("AsyncPutImage", "ObjectNull");
            return;
        }

        File file = new File(localFile);
        if (!file.exists()) {
            Log.w("AsyncPutImage", "FileNotExist");
            Log.w("LocalFile", localFile);
            return;
        }


        // 构造上传请求
        PutObjectRequest put = new PutObjectRequest(ossTokenObject.getBucket(), object, localFile);

        if (ossTokenObject.getCallbackUrl() != null) {
            // 传入对应的上传回调参数，这里默认使用OSS提供的公共测试回调服务器地址
            put.setCallbackParam(new HashMap<String, String>() {
                {
                    put("callbackUrl", ossTokenObject.getCallbackUrl());
                    //callbackBody可以自定义传入的信息
                    put("callbackBody", ossTokenObject.getCallbackParam());
                    put("callbackBodyType", ossTokenObject.getCallbackBodyType());
                }
            });
        }

        // 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
//                AppLog.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
                int progress = (int) (100 * currentSize / totalSize);
                if (uploadCallback != null) {
                    uploadCallback.onProgress(progress);
                }
            }
        });

        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                AppLog.d("success", "\nETag: " + result.getETag()
                        + "\nRequestId: " + result.getRequestId()
                        + "\nCallback: " + result.getServerCallbackReturnBody());
                ThreadUtil.MAIN_THREAD_HANDLER.post(new Runnable() {
                    @Override
                    public void run() {
                        if (uploadCallback != null) {
                            uploadCallback.onSuccess(getReturnUrl(object));
                        }
                    }
                });

            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                String info = "";
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                    info = clientExcepion.toString();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                    info = serviceException.toString();
                }
                if (uploadCallback != null) {
                    uploadCallback.onFailure(info);
                }
            }
        });
    }

    public interface UploadCallback {

        public void onFailure(String errorMessage);

        public void onSuccess(String url);

        public void onProgress(int progress);

    }


}
